package com.zktravel.service.product;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.odianyun.util.BeanUtils;
import com.odianyun.util.db.query.PageVO;
import com.zktravel.constants.CommonConstant;
import com.zktravel.constants.ProductConstant;
import com.zktravel.core.exception.VisibleException;
import com.zktravel.core.session.SessionContext;
import com.zktravel.enums.CodeEnum;
import com.zktravel.mapper.PlProductMapper;
import com.zktravel.mapper.TaProductMapper;
import com.zktravel.model.dto.product.PlProductDTO;
import com.zktravel.model.dto.product.ProductItem2C;
import com.zktravel.model.dto.product.TaProductDTO;
import com.zktravel.model.po.CusCoupon;
import com.zktravel.model.po.PlProduct;
import com.zktravel.model.po.TaProduct;
import com.zktravel.model.vo.common.SimpleDataVO;
import com.zktravel.model.vo.product.PlProductVO;
import com.zktravel.model.vo.product.TaProductVO;
import com.zktravel.service.BaseServiceImpl;
import com.zktravel.service.order.CusCouponService;

@Service
public class PlProductServiceImpl extends BaseServiceImpl implements PlProductService {

    @Resource
    private PlProductMapper plProductMapper;
    @Resource
    private TaProductMapper taProductMapper;
    @Resource
    private CusCouponService cusCouponService;

    //获取商品列表
    @Override
    public PageVO<PlProductVO> listPage(PlProductDTO productDTO, Long userId) {
        PageHelper.startPage(productDTO.getPageNo(), productDTO.getPageSize());

        if (null != productDTO.getCategoryId()) {
            List<Long> categoryIdList = new ArrayList<>();
            categoryIdList.add(productDTO.getCategoryId());
            productDTO.setCategoryIdList(categoryIdList);
        }

        productDTO.setIsVip(this.getUser(userId).isVip());
        List<PlProductVO> voList = plProductMapper.list(productDTO);
        return new PageVO<>(((Page) voList).getTotal(), voList);
    }

    //调价
    @Override
    public PlProductVO updatePrice(TaProductDTO dto, Long shopId) {
        //根据id获取商品信息
    	PlProductVO result = new PlProductVO();
        PlProductVO product = taProductMapper.selectProdByTpid(dto.getId(), shopId);
        if (null != product) {
            if (null != product.getMinPrice() && dto.getSellPrice().compareTo(product.getMinPrice()) < 0) {
                throw new VisibleException(CodeEnum.SELL_PRICE_LT_MIN_PRICE);
            }
            TaProduct taProduct = new TaProduct();
            taProduct.setSellPrice(dto.getSellPrice());
            taProduct.setId(dto.getId());
            taProduct.setShopId(shopId);
            taProductMapper.update(taProduct);
            
            PlProductDTO queryDto = new PlProductDTO();
            queryDto.setId(dto.getId());
            
            result = this.getInfo(queryDto, shopId, CommonConstant.PLATFORM_TYPE_B);
        }
        
		return result;
    }

    //上下架
    @Override
    public void updateStatus(TaProductDTO dto, Long shopId) {
        TaProduct taProduct = new TaProduct();
        taProduct.setStatus(dto.getStatus());
        taProduct.setId(dto.getId());
        taProduct.setShopId(shopId);
        taProductMapper.update(taProduct);
    }

    //获取商品详情
    @Override
    public PlProductVO getInfo(PlProductDTO dto, Long shopId, Integer platform) {
        Long userId = SessionContext.getUserId();

        TaProductVO taProduct = taProductMapper.selectById(dto.getId(), shopId);
        if (null == taProduct) {
            throw new VisibleException(CodeEnum.PRODUCT_NOT_EXIST);
        }

        PlProduct product = plProductMapper.selectById(taProduct.getProductId());
        if (null == product) {
            throw new VisibleException(CodeEnum.PRODUCT_NOT_EXIST);
        }

        PlProductVO vo;
        vo = BeanUtils.copyProperties(product, PlProductVO.class);
        // 成本价格用 ta_product 表的
        vo.setMarketPrice(taProduct.getMarketPrice());
        vo.setMarketPriceVip(taProduct.getMarketPrice());
        vo.setMinPrice(taProduct.getMarketPrice());

        vo.setSellPrice(taProduct.getSellPrice());
        vo.setStatus(taProduct.getStatus());
        vo.setId(dto.getId());
        vo.setSellNum(product.getSellNum() + product.getvSellNum());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (null != platform && CommonConstant.PLATFORM_TYPE_C.equals(platform)) {
            //隐藏敏感价格
            vo.setMarketPrice(null);
            vo.setMarketPriceVip(null);
            vo.setProfitAmt(null);

            //判断是否领取过优惠券，获取优惠券金额
            vo.setUserHasCoupon(false);
            CusCoupon coupon = cusCouponService.exist(dto.getId(), shopId, userId);
            if (null != coupon) {
                String expireDate = sdf.format(new Date((long) coupon.getExpireTime() * 1000));
                vo.setUserHasCoupon(true);
                vo.setUserCouponAmt(coupon.getAmt());
                vo.setCouponExpireTime(coupon.getExpireTime());
                vo.setCouponExpireDate(expireDate);
            }
        }

        return vo;
    }

    //凑单商品
    @Override
    public PageVO<PlProductVO> togeListPage(PlProductDTO dto, Integer platformType) {
        //售价1-500，库存大于0，价格从高到底
        PageHelper.startPage(dto.getPageNo(), dto.getPageSize());

        dto.setPriceMin(ProductConstant.PRICE_MIN);
        if (CommonConstant.PLATFORM_TYPE_B.equals(platformType)) {
            dto.setPriceMax(ProductConstant.PRICE_MAX_B);
        } else {
            dto.setPriceMax(ProductConstant.PRICE_MAX_C);
        }
        dto.setPlatformType(platformType);
        List<PlProductVO> voList = plProductMapper.togeListPage(dto);
        if (CommonConstant.PLATFORM_TYPE_C.equals(platformType)) {
            voList.stream().forEach(item -> {
                item.setMarketPrice(null);
                item.setMarketPriceVip(null);
                item.setProfitAmt(null);
            });
        }

        return new PageVO<>(((Page) voList).getTotal(), voList);
    }

    //商品名模糊查询
    @Override
    public List<SimpleDataVO> inklingQuery(String name, Long shopId) {
        return taProductMapper.inklingQuery(name, shopId);
    }

    /**
     * @param productDTO
     * @return 返回类型
     * @throws
     * @Title: listPageClient
     * @Description: C端商品列表
     * @author diaoxingguo
     * @date 2018年6月23日
     */
    @Override
    public PageVO<ProductItem2C> listPageClient(PlProductDTO productDTO) {
        PageHelper.startPage(productDTO.getPageNo(), productDTO.getPageSize());

        if (null != productDTO.getCategoryId()) {
            List<Long> categoryIdList = new ArrayList<>();
            categoryIdList.add(productDTO.getCategoryId());
            productDTO.setCategoryIdList(categoryIdList);
        }
        List<PlProductVO> voList = plProductMapper.list(productDTO);
        Long total = ((Page) voList).getTotal();
        List<ProductItem2C> list = BeanUtils.copyList(voList, ProductItem2C.class);
        return new PageVO<>(total, list);
    }

}
